<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath %>" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="/static/jquery-1.8.2.min.js"></script>
<script type="text/javascript">
$(function(){
	var userId = ${userId };
	
	if(typeof(WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
    }else{
        console.log("您的浏览器支持WebSocket");
        
      	// 实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
        var socketUrl="<%=basePath %>im/" + userId;
		socketUrl = socketUrl.replace("https", "ws").replace("http", "ws");
		console.log(socketUrl)
		var socket = new WebSocket(socketUrl);
		//打开事件
		socket.onopen = function() {
			console.log("websocket已打开");
			//socket.send("这是来自客户端的消息" + location.href + new Date());
		};
		//获得消息事件
		socket.onmessage = function(msg) {
			console.log("获取消息：" + msg.data);
			var obj = JSON.parse(msg.data);
			//发现消息进入    开始处理前端触发逻辑
			console.log(obj);
			if(obj.code == 0){
				console.log(obj.content)
				if(obj.content != null && obj.content != 'undefined' && obj.content != ""){
					$("#ul_id").append("<li>"+ obj.content +"</li>")
				}
			}else if (obj.code == -2){
				$("#ul_id").append("<li>"+ obj.msg +"</li>")
			}
		};
		//关闭事件
		socket.onclose = function() {
			console.log("websocket已关闭");
		};
		//发生了错误事件
		socket.onerror = function() {
			console.log("websocket发生了错误");
		}
	}

	$("#btn").click(function() {
		if(socket == null){
			alert("服务关闭了")
		}
		
		var param = {};
		param["toUserId"] = $("#toUserId").val();
		param["content"] = $("#content").val();
		var params = JSON.stringify(param);
		console.log("发送：" + params);
		socket.send(params);
	})
})
</script>
</head>
<body>
	<div class="div_msg">
		<textarea name="content" cols="40" rows="3" id="content"></textarea>
		<p>接收者：<input id="toUserId" name="toUserId" type="text" value="${toUserId }" /></p>
		<button id="btn">发送</button>
	</div>
	
	<div>
		<ul id="ul_id">
		</ul>
	</div>
</body>
</html>